/*
 * @# CircleController.java 2011-12-22 上午11:49:30
 * 
 * Copyright (C) 2010 - 2011 广州羿安信息科技有限公司
 * Guangzhou ianswer information technology co. ltd.
 * 
 * All rights reserved!
 */
package com.ianswer.px.user.action;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ianswer.common.util.Feedback;
import com.ianswer.px.common.SessionContextHolder;
import com.ianswer.px.common.annotation.SessionAware;
import com.ianswer.px.user.entity.Circle;
import com.ianswer.px.user.entity.Follow;
import com.ianswer.px.user.entity.UserBaseInfo;
import com.ianswer.px.user.entity.UserSession;
import com.ianswer.px.user.service.CircleService;
import com.ianswer.px.user.service.FollowCircleService;
import com.ianswer.px.user.service.FollowService;

/**
 * @author pananz
 */
@SessionAware
@Controller
public class CirclesController {

	private static final int max = 20;

	@Resource(name = "circleService")
	private CircleService circleService;

	@Resource(name = "followCircleService")
	private FollowCircleService followCircleService;

	@Resource(name = "followService")
	private FollowService followService;

	/**
	 * 全部关注列表
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/follow", method = RequestMethod.GET)
	public String follow(HttpServletRequest request, Model model) {
		int skip = 0;
		String rp = request.getParameter("rp");
		if (StringUtils.isNotBlank(rp)) {
			skip = Integer.parseInt(rp);
		}
		Long userId = SessionContextHolder.getUserId();
		List<Circle> circles = getCircles(userId);

		List<UserBaseInfo> follows = followService.queryFollow(userId, circles, skip, max);
		model.addAttribute("follows", follows);
		model.addAttribute("circles", circles);
		return "user/follow";
	}

	private List<Circle> getCircles(Long userId) {
		List<Circle> circles = SessionContextHolder.currentUser().getCircles();
		if (CollectionUtils.isEmpty(circles)) {
			circles = circleService.query(userId);
			UserSession userSession = SessionContextHolder.currentUser();
			userSession.setCircles(circles);
		}
		return circles;
	}

	/**
	 * 相互关注列表
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/mutual", method = RequestMethod.GET)
	public String mutual(HttpServletRequest request, Model model) {
		int skip = 0;
		String rp = request.getParameter("rp");
		if (StringUtils.isNotBlank(rp)) {
			skip = Integer.parseInt(rp);
		}
		Long userId = SessionContextHolder.getUserId();
		List<Circle> circles = getCircles(userId);

		List<UserBaseInfo> mutuals = followService.queryMutual(userId, circles, skip, max);
		model.addAttribute("mutuals", mutuals);
		model.addAttribute("circles", circles);
		return "user/follow";
	}

	/**
	 * 粉丝列表
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/fans", method = RequestMethod.GET)
	public String fans(HttpServletRequest request, Model model) {
		int skip = 0;
		String rp = request.getParameter("rp");
		if (StringUtils.isNotBlank(rp)) {
			skip = Integer.parseInt(rp);
		}
		Long userId = SessionContextHolder.getUserId();
		List<Circle> circles = getCircles(userId);

		List<UserBaseInfo> fans = followService.queryFans(userId, skip, max);
		model.addAttribute("fans", fans);
		model.addAttribute("circles", circles);
		return "user/fans";
	}

	/**
	 * 圈内好友列表
	 * @param circleId
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/circles/{circleId}", method = RequestMethod.GET)
	public String friends(@PathVariable String circleId, HttpServletRequest request, Model model) {
		int skip = 0;
		String rp = request.getParameter("rp");
		if (StringUtils.isNotBlank(rp)) {
			skip = Integer.parseInt(rp);
		}
		Long userId = SessionContextHolder.getUserId();
		List<Circle> circles = getCircles(userId);
		List<UserBaseInfo> friends = followService.queryFollowByCircle(Long.parseLong(circleId), userId, circles, skip,
				max);

		model.addAttribute("circles", circles);
		model.addAttribute("friends", friends);
		model.addAttribute("circleId", circleId);
		return "user/follow";
	}

	@RequestMapping(value = "/invite", method = RequestMethod.GET)
	public String invite(Model model) {
		return "user/invite";
	}

	@RequestMapping(value = "/find", method = RequestMethod.GET)
	public String find(Model model) {
		return "user/find";
	}

	/**
	 * 包含的圈圈
	 * @return
	 */
	@RequestMapping(value = "/user/circles", method = RequestMethod.GET)
	public List<Circle> showCircle() {
		return getCircles(SessionContextHolder.getUserId());
	}

	/**
	 * 创建圈子
	 * @param circle
	 * @param model
	 * @param session
	 */
	@RequestMapping(value = "/circles/create", method = RequestMethod.POST)
	public @ResponseBody
	Feedback create(@RequestParam String circle) {
		try {
			String[] circleNames = StringUtils.split(circle, ",");
			Long userId = SessionContextHolder.getUserId();
			Long lastCircleId = circleService.insertList(circleNames, userId);
			//圈子session内容重新设定
			List<Circle> circles = circleService.query(userId);
			UserSession userSession = SessionContextHolder.currentUser();
			userSession.setCircles(circles);
			return Feedback.success("t").setObj(lastCircleId);
		} catch (Exception e) {
			return Feedback.fail("创建圈子出错");
		}
	}

	/**
	 * 加入圈子
	 * @param circleId
	 * @param who
	 * @param model
	 * @param session
	 */
	@RequestMapping(value = "/circles/{circleId}/{whom}/join", method = RequestMethod.POST)
	public @ResponseBody
	Feedback join(@PathVariable String circleId, @PathVariable String whom, Model model) {
		if (StringUtils.isBlank(whom) || StringUtils.isBlank(circleId)) {
			return Feedback.fail("参数不完整");
		}
		try {
			Long who = SessionContextHolder.getUserId();
			Follow follow = followService.get(who, Long.parseLong(whom));
			if (null == follow) {
				return Feedback.fail("尚未加入关注");
			}
			follow = followCircleService.insert(Long.parseLong(circleId), follow);
			List<Long> checkCircleIds = follow.getCircleIds();
			List<Circle> checkCircles = getCheckCircle(checkCircleIds);
			String circleNameStr = getCircleName(checkCircles);

			return Feedback.success("t").setObj(circleNameStr);
		} catch (Exception e) {
			e.printStackTrace();
			return Feedback.fail("加入圈子出错");
		}
	}

	private List<Circle> getCheckCircle(List<Long> circleIds) {
		List<Circle> checkCircles = new ArrayList<Circle>();
		List<Circle> allCircles = getCircles(SessionContextHolder.getUserId());
		if (CollectionUtils.isEmpty(circleIds) || CollectionUtils.isEmpty(allCircles)) {
			return null;
		}
		for (Circle allCircle : allCircles) {
			if (circleIds.contains(allCircle.getId())) {
				checkCircles.add(allCircle);
			}
		}
		return checkCircles;
	}

	private String getCircleName(List<Circle> checkCircles) {

		List<String> circleNames = new ArrayList<String>();
		if (CollectionUtils.isEmpty(checkCircles)) {
			return null;
		}
		for (Circle circle : checkCircles) {
			circleNames.add(circle.getCircleName());
		}
		return StringUtils.join(circleNames, "|");
	}

	/**
	 * 退出圈子
	 * @param circleId
	 * @param who
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/circles/{circleId}/{whom}/out", method = RequestMethod.POST)
	public @ResponseBody
	Feedback remove(@PathVariable String circleId, @PathVariable String whom, Model model) {
		if (StringUtils.isBlank(whom) || StringUtils.isBlank(circleId)) {
			return Feedback.fail("参数不完整");
		}
		try {
			Long who = SessionContextHolder.getUserId();
			Follow follow = followService.get(who, Long.parseLong(whom));
			if (null == follow) {
				return Feedback.fail("尚未加入关注");
			}
			follow = followCircleService.delete(Long.parseLong(circleId), follow);
			List<Long> checkCircleIds = follow.getCircleIds();
			List<Circle> checkCircles = getCheckCircle(checkCircleIds);
			String circleNameStr = getCircleName(checkCircles);
			return Feedback.success("t").setObj(circleNameStr);
		} catch (Exception e) {
			return Feedback.fail("加入圈子出错");
		}
	}

	/**
	 * 设定关注
	 * @param whom
	 * @param model
	 * @param session
	 */
	@RequestMapping(value = "/circle/{whom}/follow", method = RequestMethod.POST)
	public @ResponseBody
	Feedback follow(@PathVariable String whom) {
		try {
			Long userId = SessionContextHolder.getUserId();
			followService.insert(userId, Long.parseLong(whom));
			return Feedback.success("t");
		} catch (Exception e) {
			return Feedback.fail("关注失败");
		}
	}

	/**
	 * 取消关注
	 * @param whom
	 * @param model
	 */
	@RequestMapping(value = "/circle/{whom}/remove", method = RequestMethod.POST)
	public @ResponseBody
	Feedback remove(@PathVariable String whom) {
		try {
			Long who = SessionContextHolder.getUserId();
			followService.delete(who, Long.parseLong(whom));
			return Feedback.success("t");
		} catch (Exception e) {
			return Feedback.fail("取消关注失败");
		}
	}
}
